package com.ysb.searchserver;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.sql.rowset.CachedRowSet;

import com.ysb.searchserver.share.SearchProvider;

public class SearchProviderImpl implements SearchProvider {

	
	private static final Map<String, Integer> Words = new ConcurrentHashMap<String, Integer>(50*1024);
	
	private ExamSearcher englishSearcher;
	
	public SearchProviderImpl() {
		
	}
	
	public void init() throws Throwable {
		loadWords();
		loadExams();
	}
	
	private void loadWords() throws Throwable {
		CachedRowSet crs = DBUtil.select("select id, name from vocabulary_detail");
		while(crs.next()) {
			Words.put(crs.getString("name"), crs.getInt("id"));
		}
	}
	
	private void loadExams() throws Throwable{
		englishSearcher = new EnglishExamSearcher();
	}
	
	@Override
	public void addWord(String word, int id) {
		Words.put(word, id);
		
	}

	@Override
	public void delWord(String word) {
		Words.remove(word);
	}

	@Override
	public int queryWord(String word) {
		Integer id = Words.get(word);
		if(id == null) {
			return SearchProvider.NO_RESULT;
		}
		return id;
	}

	@Override
	public int deleteDoc(int docId) {
		try {
			englishSearcher.deleteDoc(docId);
		}
		catch(Throwable th) {
			return SYSERROR;
		}
		return 0;
	}

	@Override
	public void updateDoc(int docId, String sentence) {
		return ;
		
	}

	@Override
	public List<Integer> queryExamByWords(String words) {
		try {
			ExamSearcher seacher = getSeacher(words); 
			List<Integer> list = seacher.search(words);
			if(list.isEmpty()) {
				BizLogger.info("queryExamByWords", "NORESULT", words);
			}
			else {
				BizLogger.info("queryExamByWords", "HASRESULT", list.size(), words);
			}
			return list;
		}
		catch(Throwable th) {
			BizLogger.error(th, "queryExamByWords", "SYSERROR", words);
		}
		return new ArrayList<Integer>(0);
	}
	
	private ExamSearcher getSeacher(String words) {
		if(isEnglish(words)) {
			return englishSearcher;
		}
		return null;//TODO 翻译
	}
	
	private boolean isEnglish(String words) {
		char ch = 0;
		int englishwordss = 0;
		for(int i=0;i<words.length();i++) {
			ch = words.charAt(i);
			if(ch>=65 && ch<=122) {
				++englishwordss;
			}
		}
		return (englishwordss*1.0/words.length())>0.9;
		
	}

}
